package com.fuyu.system.controller;


import com.fuyu.common.model.R;
import com.fuyu.common.web.controller.BaseController;
import com.fuyu.component.redis.service.RedisService;
import com.fuyu.system.anno.IgnoreWebSecurity;
import com.fuyu.system.models.form.SysLoginForm;
import com.fuyu.system.models.vo.login.CaptchaVO;
import com.fuyu.system.models.vo.login.LoginVO;
import com.fuyu.system.service.SysLoginService;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;


@CrossOrigin
@Slf4j
@Tag(name = "系统登入")
@RequestMapping("/sys/login")
@RestController
public class SysLoginController extends BaseController {

    @Autowired
    private SysLoginService sysLoginService;


    @Autowired
    private RedisService redisService;


    @IgnoreWebSecurity
    @Operation(summary = "登入验证码")
    @GetMapping("/captcha")
    public R<Object> captcha() {
        try {
            // 创建验证码对象
            Captcha captcha = new ArithmeticCaptcha();

            // 生成验证码编号
            String captchaKey = UUID.randomUUID().toString();

            CaptchaVO captchaVO = CaptchaVO.builder()
                    .captchaBase64(captcha.toBase64())
                    .captchaKey(captchaKey)
                    .build();

            redisService.setObject(captchaKey, captcha.text(), 1, TimeUnit.MINUTES);

            log.info("Captcha:{}", captcha.text());

            log.info("CaptchaKey{}", captchaKey);
            Object attribute = redisService.getObject(captchaKey);

            log.info("attribute:{} ", attribute);

            return R.success(captchaVO);
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.failed("获取验证码失败");
        }

    }


    //@PreAuthorize("hasAuthority('sys:use:test')")
    @IgnoreWebSecurity
    @Operation(summary = "用户登入")
    @PostMapping
    public R<LoginVO> login(@RequestBody @Valid SysLoginForm params) {


        //验证码redis的key
        String captchaKey = params.getCaptchaKey();

        //验证码值
        Object redisCaptchaKey = redisService.getObject(captchaKey);

        //验证码是否过期
        if (redisCaptchaKey == null) {
            return R.failed("验证码过期");
        }

        //验证码对比
        if (!params.getCaptcha().equals(redisCaptchaKey)) {
            return R.failed("验证码错误");
        }

        return R.success(sysLoginService.login(params));
    }
}
